<?php
class UsersController extends AppController{
	
	var $helpers = Array("Form");
	
	var $uses = array("User","Group");
	
	function beforeFilter() {
    	parent::beforeFilter(); 
    	$this->Auth->allowedActions = array('login','logout','redirectuser');
	}
	
	public function index(){
		$this->set('users',$this->User->find('all'));
	}
	
	/**
	 * Init the aco_aro table in the database
	 * @return unknown_type
	 */
	function initDB() {
	    $group =& $this->User->Group;
	    //Allow admins to everything
	    $group->id = 1;     
	    $this->Acl->allow($group, 'controllers');
	 
	    //allow managers to posts and widgets
	    //$group->id = 2;
	    //$this->Acl->deny($group, 'controllers');
	    //$this->Acl->allow($group, 'controllers/Posts');
	    //$this->Acl->allow($group, 'controllers/Widgets');
	 
	    //allow users to only add and edit on posts and widgets
	    //$group->id = 3;
	    //$this->Acl->deny($group, 'controllers');        
	    //$this->Acl->allow($group, 'controllers/Posts/add');
	    //$this->Acl->allow($group, 'controllers/Posts/edit');        
	    //$this->Acl->allow($group, 'controllers/Widgets/add');
	    //$this->Acl->allow($group, 'controllers/Widgets/edit');
	}
	
	/**
	 * Creates user account
	 * @return void
	 */
	public function create(){
		
		if(!empty($this->data)){
			
			if($this->User->save($this->data)){
				$this->Session->setFlash("User created");
			}
		}
		
		$groups = $this->Group->find('all');
		
		$groups_array = array();
		
		foreach($groups as $group){
			$groups_array[$group['Group']['id']] = $group['Group']['name'];	
		}
		$this->set('groups',$groups_array);
	}
	
	
	public function redirectuser(){
		
		$user = $this->Session->read('Auth.User');
		
		if(!$user){
			
			$this->redirect("/users/login");
			
		}else{
			
			$params = array('conditions'=>array("Group.id"=>$user['group_id']));
			$group = $this->Group->find('first',$params);	

			switch ($group['Group']['name']){
				case 'Clients': $this->redirect('/clients'); break;
				case 'Administrators': $this->redirect('/companies'); break;
				default: $this->redirect('/users/login');
			}
		}
		
	}
	
	/**
	 * Login
	 * @return void
	 */
	public function login(){		
		if ($this->Session->read('Auth.User')) {
			$this->Session->setFlash('You are logged in!');
			//$this->redirect('/', null, false);
		}		
	}
	
	/**
	 * Logout
	 * @return void
	 */
	public function logout(){
		$this->Session->setFlash('Good-Bye');
		$this->redirect($this->Auth->logout());		
	}
}